/*******************************************************************************
 * 文件名: WebResult.java
 * 版　权: Web结果
 * 创建人: Dean Huang <huangjing@tydic.com>
 * 日　期: Jul 19, 2017 
 * 描　述: 文件描述
 * 版　本: 1.0
 *******************************************************************************/

package com.z1.core.web.model;

import java.util.HashMap;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.z1.core.JackJsonUtil;

import io.swagger.annotations.ApiModel;

@ApiModel(value="WebResult 接口结果对象")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class WebResult extends HashMap<String, Object> implements WebResultConst {
	
	private static final Logger log = Logger.getLogger(WebResult.class);

	private static final long serialVersionUID = -9183375559041593896L;

	// 正常
	public static final int CODE_OK = 200;
	// 异常
	public static final int CODE_BAD_REQUEST = 400;
	// 工作区不存在
	public static final int CODE_WORKSPACE_NOT_EXIST = 403;
	// 系统内部异常
	public static final int CODE_SYS_ERR = -1;

	public WebResult setCode(Integer errCode) {
		this.put(CODE_KEY, errCode == null ? CODE_SYS_ERR : errCode);
		return this;
	}

	public WebResult code(Integer errCode) {
		return this.setCode(errCode);
	}

	public WebResult setMsg(String msg) {
		if (msg == null) {
			this.remove(MSG_KEY);
		} else {
			this.put(MSG_KEY, msg);
		}
		return this;
	}

	public WebResult msg(String msg) {
		return this.setMsg(msg);
	}

	public WebResult setData(Object data) {
		return this.setData(DATA_KEY, data);
	}

	public WebResult data(Object data) {
		return this.setData(data);
	}

	public WebResult setData(String key, Object data) {
		success();
		if (data == null) {
			this.remove(key);
		} else {
			this.put(key, data);
		}
		return this;
	}

	public WebResult setMsg(Throwable e) {
		log.error("", e);
		setCode(CODE_SYS_ERR);
		return setMsg("出现点小状况");// 屏蔽真实异常信息显示到前端
	}

	public WebResult success() {
		return success(null);
	}

	public WebResult success(String msg) {
		setCode(CODE_OK);
		setMsg(msg);
		return this;
	}

	public WebResult failed() {
		return failed(CODE_BAD_REQUEST, null);
	}

	public WebResult failed(String msg) {
		return failed(CODE_BAD_REQUEST, msg);
	}

	public WebResult failed(int code, String msg) {
		setCode(code);
		setMsg(msg);
		return this;
	}

	@Override
	public String toString() {
		try {
			return JackJsonUtil.toJSONString(this, true);
		} catch (Exception e) {
			log.error("------", e);
			return "{\"code\":" + CODE_SYS_ERR + ",\"msg\":\"出现点小状况\"}";
		}
	}

}
